<template>
  <div class="flow-rate">
    <a-card title="流量统计">
      <!-- 统计卡片 -->
      <a-row :gutter="24" class="statistics-cards" v-if="$hasPermission('todayStatistic')">
        <a-col :span="6">
          <div class="stat-card python-card">
            <div class="card-content">
              <div class="card-title">Python模型调用量</div>
              <div class="card-subtitle">今日</div>
              <div class="card-value">{{ todayStats.P || 0 }}</div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="stat-card pmml-card">
            <div class="card-content">
              <div class="card-title">PMML模型调用量</div>
              <div class="card-subtitle">今日</div>
              <div class="card-value">{{ todayStats.J || 0 }}</div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="stat-card scorecard-card">
            <div class="card-content">
              <div class="card-title">评分卡调用量</div>
              <div class="card-subtitle">今日</div>
              <div class="card-value">{{ todayStats.GM || 0 }}</div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="stat-card total-card">
            <div class="card-content">
              <div class="card-title">模型调用总量</div>
              <div class="card-subtitle">今日</div>
              <div class="card-value">{{ todayStats.totalCount || 0 }}</div>
            </div>
          </div>
        </a-col>
      </a-row>

      <!-- 模型调用量统计情况 -->
      <div class="chart-section" v-if="$hasPermission('statistics')">
        <div class="chart-header">
          <h3>模型调用量统计情况</h3>
          <div class="chart-controls">
            <div class="date-picker">
              <span>统计时间</span>
              <a-button-group style="margin-right: 8px">
                <a-button :type="timeType === 'day' ? 'primary' : 'default'" @click="switchTimeType('day')">
                  按天
                </a-button>
                <a-button :type="timeType === 'month' ? 'primary' : 'default'" @click="switchTimeType('month')">
                  按月
                </a-button>
              </a-button-group>
              <template v-if="timeType === 'day'">
                <a-range-picker
                  v-model="dateRange"
                  format="YYYY-MM-DD"
                  @change="handleDateChange"
                  :allowClear="false"
                  :disabledDate="disabledDate"
                />
              </template>
              <template v-else>
                <a-month-picker
                  v-model="startMonth"
                  placeholder="开始月份"
                  format="YYYY-MM"
                  @change="handleStartMonthChange"
                  :allowClear="false"
                  :disabledDate="disabledStartMonth"
                  style="margin-right: 8px"
                />
                <span style="margin: 0 4px">至</span>
                <a-month-picker
                  v-model="endMonth"
                  placeholder="结束月份"
                  format="YYYY-MM"
                  @change="handleEndMonthChange"
                  :allowClear="false"
                  :disabledDate="disabledEndMonth"
                />
              </template>
            </div>
          </div>
        </div>

        <div class="chart-wrapper">
          <div class="chart-toolbar">
            <a-tooltip title="柱状图">
              <a-button
                :type="chartType === 'bar' ? 'primary' : 'default'"
                @click="switchChartType('bar')"
                icon="bar-chart"
                size="small"
                shape="circle"
              />
            </a-tooltip>
            <a-tooltip title="折线图">
              <a-button
                :type="chartType === 'line' ? 'primary' : 'default'"
                @click="switchChartType('line')"
                icon="line-chart"
                size="small"
                shape="circle"
              />
            </a-tooltip>
            <a-tooltip title="导出" v-if="$hasPermission('exportStatistics')">
              <a-button @click="handleExport" icon="download" :loading="loading" size="small" shape="circle" />
            </a-tooltip>
          </div>
          <echart :option="chartOption" v-if="chartOption" />
          <div v-else class="empty-state">
            <a-empty description="暂无数据" />
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script>
import { Echart } from '@/components'
import { statisticsToday, statistics, exportStatistics } from '@/api/flowRate'
import moment from 'moment'

export default {
  name: 'FlowRate',
  components: {
    Echart,
  },
  data() {
    return {
      timer: null, // 定时器
      todayStats: {
        P: 0,
        J: 0,
        GM: 0,
        totalCount: 0,
      },
      dateRange: [moment().subtract(7, 'days'), moment()],
      startMonth: moment().subtract(3, 'months').startOf('month'),
      endMonth: moment().startOf('month'),
      chartOption: null,
      loading: false,
      timeType: 'day', // 'day' 或 'month'
      pickerType: 'date', // 'date' 或 'month'
      chartType: 'bar', // 'bar' 或 'line'
    }
  },
  mounted() {
    this.loadTodayStats()
    this.loadChartData()
    // 设置定时器，每3分钟刷新一次数据
    this.timer = setInterval(() => {
      this.loadTodayStats()
      this.loadChartData()
    }, 3 * 60 * 1000) // 3分钟 = 180000毫秒
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  methods: {
    // 加载今日统计数据
    async loadTodayStats() {
      try {
        const response = await statisticsToday()
        if (response.code === 200 && response.data) {
          this.todayStats = {
            P: response.data.P || 0,
            J: response.data.J || 0,
            GM: response.data.GM || 0,
            totalCount: (response.data.P || 0) + (response.data.J || 0) + (response.data.GM || 0),
          }
        }
      } catch (error) {
        console.error('加载今日统计数据失败:', error)
        this.$message.error('加载今日统计数据失败')
      }
    },

    // 加载图表数据
    async loadChartData() {
      try {
        this.loading = true
        let startTime, endTime

        if (this.timeType === 'day') {
          ;[startTime, endTime] = this.dateRange
        } else {
          startTime = this.startMonth
          endTime = this.endMonth
        }

        const params = {
          startTime: startTime.valueOf().toString(),
          endTime: endTime.valueOf().toString(),
          cycle: this.timeType === 'day' ? 'D' : 'M',
        }

        const response = await statistics(params)
        if (response.code === 200 && response.data) {
          this.generateChartOption(response.data)
        }
      } catch (error) {
        console.error('加载图表数据失败:', error)
        this.$message.error('加载图表数据失败')
      } finally {
        this.loading = false
      }
    },

    // 生成图表配置
    generateChartOption(data) {
      const { statisticsLabels, scoreCardList, pmmlList, pythonList } = data

      // 计算总量数据
      const totalList = statisticsLabels.map((_, index) => {
        const scoreCard = scoreCardList[index] || 0
        const pmml = pmmlList[index] || 0
        const python = pythonList[index] || 0
        return scoreCard + pmml + python
      })

      this.chartOption = {
        title: {
          text: '模型调用量统计情况',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            shadowStyle: {
              color: 'rgba(24, 144, 255, 0.2)',
              opacity: 0.5
            },
            label: {
              backgroundColor: 'rgba(24, 144, 255, 0.8)',
              borderColor: '#1890ff',
              borderWidth: 1,
              color: '#fff'
            }
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e6e6e6',
          borderWidth: 1,
          borderRadius: 8,
          padding: [12, 16],
          textStyle: {
            color: '#333',
            fontSize: 13,
            lineHeight: 20
          },
          extraCssText: 'box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25), 0 2px 8px rgba(0, 0, 0, 0.1);',
          formatter: function(params) {
            let html = `<div style="font-weight: 600; margin-bottom: 8px; color: #262626;">${params[0].axisValue}</div>`

            // 按照指定顺序显示数据：总量、Python、PMML、评分卡
            const order = ['总量', 'Python', 'PMML', '评分卡']
            const colors = {
              '总量': '#1890ff',
              'Python': '#52c41a',
              'PMML': '#722ed1',
              '评分卡': '#ff9500'
            }

            order.forEach(name => {
              const param = params.find(p => p.seriesName === name)
              if (param) {
                const color = colors[name] || param.color
                html += `
                  <div style="display: flex; align-items: center; margin-bottom: 4px;">
                    <span style="display: inline-block; width: 10px; height: 10px; background-color: ${color}; border-radius: 50%; margin-right: 8px;"></span>
                    <span style="flex: 1; color: #666;">${param.seriesName}：</span>
                    <span style="font-weight: 600; color: #262626;">${param.value.toLocaleString()}</span>
                  </div>
                `
              }
            })

            return html
          }
        },
        legend: {
          data: ['总量', 'Python', 'PMML', '评分卡'],
          bottom: 10,
          left: 'center',
          itemGap: 20,
          textStyle: {
            fontSize: 12,
          },
          show: true,
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '20%',
          top: '20%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: statisticsLabels || [],
          axisLabel: {
            interval: 0,
            rotate: 0,
            fontSize: 12,
            margin: 8,
          },
        },
        yAxis: {
          type: 'value',
          name: '调用次数',
        },
        series: [
          {
            name: '总量',
            type: this.chartType,
            data: totalList || [],
            itemStyle: {
              color: '#1890ff',
            },
            smooth: this.chartType === 'line',
          },
          {
            name: 'Python',
            type: this.chartType,
            data: pythonList || [],
            itemStyle: {
              color: '#52c41a',
            },
            smooth: this.chartType === 'line',
          },
          {
            name: 'PMML',
            type: this.chartType,
            data: pmmlList || [],
            itemStyle: {
              color: '#722ed1',
            },
            smooth: this.chartType === 'line',
          },
          {
            name: '评分卡',
            type: this.chartType,
            data: scoreCardList || [],
            itemStyle: {
              color: '#ff9500',
            },
            smooth: this.chartType === 'line',
          },
        ],
      }
    },

    // 切换时间类型
    switchTimeType(type) {
      this.timeType = type
      this.pickerType = type === 'day' ? 'date' : 'month'

      // 根据类型设置默认时间范围
      if (type === 'day') {
        this.dateRange = [moment().subtract(7, 'days'), moment()]
      } else {
        this.startMonth = moment().subtract(3, 'months').startOf('month')
        this.endMonth = moment().startOf('month')
      }

      this.loadChartData()
    },

    // 切换图表类型
    switchChartType(type) {
      this.chartType = type
      // 重新生成图表配置
      if (this.chartOption) {
        this.loadChartData()
      }
    },

    // 导出数据
    async handleExport() {
      try {
        this.loading = true
        let startTime, endTime

        if (this.timeType === 'day') {
          ;[startTime, endTime] = this.dateRange
        } else {
          startTime = this.startMonth
          endTime = this.endMonth
        }

        const params = {
          startTime: startTime.valueOf().toString(),
          endTime: endTime.valueOf().toString(),
          cycle: this.timeType === 'day' ? 'D' : 'M',
        }

        await exportStatistics(params)
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.loading = false
      }
    },

    // 日期禁用规则
    disabledDate(current) {
      if (!current) return false

      const now = moment()
      if (this.timeType === 'day') {
        // 按天：不能超过今天，且不能选择超过14天的范围
        return current > now
      } else {
        // 按月：不能超过当前月，且不能选择超过12个月的范围
        return current > now.endOf('month')
      }
    },

    // 开始月份禁用规则
    disabledStartMonth(current) {
      if (!current) return false
      const now = moment()
      // 不能超过当前月，且不能大于结束月份
      return current > now.endOf('month') || (this.endMonth && current > this.endMonth)
    },

    // 结束月份禁用规则
    disabledEndMonth(current) {
      if (!current) return false
      const now = moment()
      // 不能超过当前月，且不能小于开始月份，且不能超过开始月份12个月
      if (current > now.endOf('month')) return true
      if (this.startMonth && current < this.startMonth) return true
      if (this.startMonth && current.diff(this.startMonth, 'months') > 12) return true
      return false
    },

    // 开始月份改变
    handleStartMonthChange(date) {
      this.startMonth = date
      // 检查结束月份是否需要调整
      if (this.endMonth && this.endMonth < date) {
        this.endMonth = date
      }
      // 检查是否超过12个月范围
      if (this.endMonth && this.endMonth.diff(date, 'months') > 12) {
        this.endMonth = date.clone().add(12, 'months')
        this.$message.warning('按月查询最多支持12个月范围，已自动调整结束月份')
      }
      // 自动加载数据
      this.loadChartData()
    },

    // 结束月份改变
    handleEndMonthChange(date) {
      this.endMonth = date
      // 检查开始月份是否需要调整
      if (this.startMonth && this.startMonth > date) {
        this.startMonth = date
      }
      // 检查是否超过12个月范围
      if (this.startMonth && date.diff(this.startMonth, 'months') > 12) {
        this.startMonth = date.clone().subtract(12, 'months')
        this.$message.warning('按月查询最多支持12个月范围，已自动调整开始月份')
      }
      // 自动加载数据
      this.loadChartData()
    },

    // 日期范围改变（按天模式）
    handleDateChange(dates) {
      if (!dates || dates.length !== 2) return

      const [start, end] = dates

      // 按天模式：检查是否超过14天
      const daysDiff = end.diff(start, 'days')
      if (daysDiff > 14) {
        this.$message.warning('按天查询最多支持14天范围')
        this.dateRange = [end.clone().subtract(14, 'days'), end]
        return
      }

      this.dateRange = dates
      // 自动加载数据
      this.loadChartData()
    },
  },
}
</script>

<style lang="less" scoped>
.flow-rate {
  .statistics-header {
    margin-bottom: 24px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      color: #262626;
    }
  }

  .statistics-cards {
    margin-bottom: 32px;

    .stat-card {
      height: 120px;
      border-radius: 8px;
      padding: 20px;
      color: white;
      position: relative;
      overflow: hidden;

      &.python-card {
        background: linear-gradient(135deg, #52c41a, #73d13d);
      }

      &.pmml-card {
        background: linear-gradient(135deg, #722ed1, #9254de);
      }

      &.scorecard-card {
        background: linear-gradient(135deg, #ff9500, #ffa940);
      }

      &.total-card {
        background: linear-gradient(135deg, #1890ff, #40a9ff);
      }

      .card-content {
        position: relative;
        z-index: 2;

        .card-title {
          font-size: 14px;
          opacity: 0.9;
          margin-bottom: 4px;
        }

        .card-subtitle {
          font-size: 12px;
          opacity: 0.7;
          margin-bottom: 12px;
        }

        .card-value {
          font-size: 32px;
          font-weight: bold;
          line-height: 1;
        }
      }
    }
  }

  .chart-section {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: #262626;
      }

      .chart-controls {
        display: flex;
        align-items: center;
        gap: 16px;
        flex-wrap: wrap;

        .date-picker {
          display: flex;
          align-items: center;
          gap: 8px;

          span {
            color: #666;
            font-size: 14px;
          }
        }

        .chart-actions {
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }

    .chart-wrapper {
      height: 480px;
      overflow: visible;
      position: relative;

      .chart-toolbar {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 10;
        display: flex;
        gap: 8px;
        background: rgba(255, 255, 255, 0.9);
        padding: 4px;
        border-radius: 6px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .empty-state {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
